//
//  BCDebugPage.m
//  Pod
//
//  Created by Basic on 2017/3/14.
//  Copyright © 2017年 naruto. All rights reserved.
//  debug 组件
//  pannel面板

#import "BCDebugPage.h"
#import "BCDebugKitPrivate.h"
#import "UIPickerView+BCPrivate.h"


#define kBCDebugPage_PickViewHeight                  150.0f

typedef void(^BCDebugPageHideBlock)(void);

@interface BCDebugPage()<UITableViewDelegate,UITableViewDataSource,UIPickerViewDataSource, UIPickerViewDelegate>
/// 配置项 table
@property (nonatomic, strong) UITableView   *tbvConfigs;
/// 是否正在显示
@property (nonatomic, assign, readwrite) BOOL   isShowing;
/// 配置选项 pickview
@property (nonatomic, strong) UIPickerView  * pvSwitch;

@property (nonatomic, copy) BCDebugPageHideBlock     hideAction;
/// debug 选择项
@property (nonatomic, strong) NSMutableArray<BCDebugItemGroup *>    *listDebugGroups;
@end

@implementation BCDebugPage
#pragma mark - system
- (instancetype)init {
    self = [super init];
    if (self) {
       
    }
    return self;
}
- (instancetype)initWithHideAction:(void(^)(void) )hideAction {
    self = [self init];
    if (self) {
        _hideAction = hideAction;
    }
    return self;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.edgesForExtendedLayout = UIRectEdgeNone;
    [self.navigationItem setTitle:@"调试面板"];
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self pageDidLoad];
}
-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    _isShowing = YES;
    [self reloadPage];
}
-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    _isShowing = NO;
}
#ifdef DEBUG
- (void)dealloc {
    NSLog(@"BCDebugPage dealloc");
    _tbvConfigs.delegate = nil;
    _tbvConfigs.dataSource = nil;
}
#endif

#pragma mark - public
- (void)reloadPage {
    [self reloadDebugConfig];
    [self.tbvConfigs reloadData];
}


#pragma mark - private
/// 页面加载的时候
-(void)pageDidLoad {
    _listDebugGroups = [[NSMutableArray alloc] init];

    UIButton *btnRight = [UIButton buttonWithType:UIButtonTypeCustom];
    [btnRight setFrame:CGRectMake(0, 0, 40, 40)];
    [btnRight setImage:BCDebugImageNamed(@"nav_btn_close") forState:UIControlStateNormal];
    [btnRight setImage:BCDebugImageNamed(@"nav_btn_close_press") forState:UIControlStateHighlighted];
    [btnRight addTarget:self action:@selector(onNavLeftItemAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *navItemRight = [[UIBarButtonItem alloc] initWithCustomView:btnRight];
    [self.navigationItem setRightBarButtonItem:navItemRight];
    //初始化 tableview
    [self.view addSubview:self.tbvConfigs];
}
- (void)reloadDebugConfig {
    [self.listDebugGroups removeAllObjects];
    //遍历config obj
    for (id<BCDebugKitProtocol> obj in self.debugConfigs) {
        BCDebugItemGroup *debugGroup = [obj bcDebugConfigSetupDebugGroup];
        if(debugGroup){
            [self.listDebugGroups addObject:debugGroup];
        }
    }
    //遍历config class
    for (Class cls in self.debugConfigClses) {
        id objDebugConfig = [[cls alloc] init];
        if(objDebugConfig && [objDebugConfig conformsToProtocol:@protocol(BCDebugKitProtocol)]){
            BCDebugItemGroup *debugGroup = [objDebugConfig bcDebugConfigSetupDebugGroup];
            if(debugGroup){
                [self.listDebugGroups addObject:debugGroup];
            }
        }
    }
}
-(void)onNavLeftItemAction:(id )sender {
    [self dismissViewControllerAnimated:YES completion:nil];
    if(self.hideAction){
        self.hideAction();
    }
}

#pragma mark - getter
-(UITableView *)tbvConfigs {
    if(!_tbvConfigs){
        //初始化 tableview
        CGRect frameTable = self.view.frame;
        _tbvConfigs = [[UITableView alloc] initWithFrame:CGRectMake(0, 0,frameTable.size.width , frameTable.size.height-40) style:UITableViewStyleGrouped];
        _tbvConfigs.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        _tbvConfigs.dataSource = self;
        _tbvConfigs.delegate = self;
        _tbvConfigs.sectionHeaderHeight = 30;
        _tbvConfigs.estimatedRowHeight = 54;
        _tbvConfigs.rowHeight = UITableViewAutomaticDimension;
        _tbvConfigs.sectionFooterHeight = 0;
        _tbvConfigs.allowsMultipleSelection = NO;
        _tbvConfigs.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        if(@available(iOS 11.0, *)) {
            _tbvConfigs.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onTableTapGesture:)];
        tapGesture.cancelsTouchesInView = false;
        [_tbvConfigs addGestureRecognizer:tapGesture];
    }
    return _tbvConfigs;
}
- (UIPickerView *)pvSwitch {
    if (!_pvSwitch) {
        CGFloat pvY = CGRectGetHeight([UIScreen mainScreen].bounds)-kBCDebugPage_PickViewHeight-64;
        if(@available(iOS 13.0, *)) {
            pvY = CGRectGetHeight([UIScreen mainScreen].bounds)-kBCDebugPage_PickViewHeight-64-54;
        }
        _pvSwitch = [[UIPickerView alloc] initWithFrame:CGRectMake(0, pvY, CGRectGetWidth([UIScreen mainScreen].bounds), kBCDebugPage_PickViewHeight)];
        _pvSwitch.dataSource = self;
        _pvSwitch.delegate = self;
        _pvSwitch.backgroundColor = [UIColor colorWithRed:230/255.0 green:230/255.0 blue:230/255.0 alpha:1];
        _pvSwitch.showsSelectionIndicator = YES;
        _pvSwitch.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
    }
    return _pvSwitch;
}


#pragma mark - UITableViewDataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.listDebugGroups.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if(self.listDebugGroups.count > section){
        BCDebugItemGroup *debugGroup = [self.listDebugGroups objectAtIndex:section];
        return [debugGroup.bcItems count];
    }
    return 0;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if(self.listDebugGroups.count <= indexPath.section){
        return nil;
    }
    BCDebugItemGroup *debugGroup = [self.listDebugGroups objectAtIndex:indexPath.section];
    NSMutableArray *listItems = debugGroup.bcItems;
    if(listItems.count <= indexPath.row){
        return nil;
    }
    BCDebugItemModel *debugItem = [listItems objectAtIndex:indexPath.row];
    static NSString *kBCTableViewCellIdentifierKey = @"kBCTableViewCellIdentifierKey";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kBCTableViewCellIdentifierKey];
    if(!cell){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:kBCTableViewCellIdentifierKey];
        cell.backgroundColor = [UIColor whiteColor];
    }
    cell.selectionStyle = debugItem.bcSelectStyle;
    cell.accessoryType = debugItem.bcAccessoryType;
    cell.textLabel.text = debugItem.bcName;
    cell.detailTextLabel.text = debugItem.bcDetail;
    cell.detailTextLabel.lineBreakMode = NSLineBreakByCharWrapping;
    cell.detailTextLabel.numberOfLines = 0;
    return cell;
}
- (nullable NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if(self.listDebugGroups.count <= section){
        return nil;
    }
    BCDebugItemGroup *debugGroup = [self.listDebugGroups objectAtIndex:section];
    return debugGroup.bcName;
}

#pragma mark - UITableViewDelegate
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if(self.listDebugGroups.count <= indexPath.section){
        return ;
    }
    BCDebugItemGroup *debugGroup = [self.listDebugGroups objectAtIndex:indexPath.section];
    NSMutableArray *listItems = debugGroup.bcItems;
    if(listItems.count <= indexPath.row){
        return ;
    }
    BCDebugItemModel *debugItem = [listItems objectAtIndex:indexPath.row];
    switch (debugItem.bcType) {
        case BCDebugItemType_Selector://如果类型是switch
        {
            if(debugItem.selectItemAction){
                debugItem.selectItemAction(debugItem,indexPath.row);
            }
            //判断 选项列表是否空
            if(debugItem.bcOptions.count>0){
                //pickview tag 赋值
                if(self.pvSwitch.superview){
                    if(self.pvSwitch.kdhTag == debugItem.bcTag){
                        //已经存在pickerView，点击同一个cell,移除pickerView，return
                        [self.pvSwitch removeFromSuperview];
                        return;
                    }
                }
                else if(!self.pvSwitch.superview){
                    [self.view addSubview:self.pvSwitch];
                }
                self.pvSwitch.kdhData = debugItem;
                [self.pvSwitch reloadAllComponents];
                [self.pvSwitch selectRow:debugItem.bcSelectOptionIndex inComponent:0 animated:YES];
            }
        }
            break;
            
        default://默认 调用item的select事件
        {
            if(debugItem.selectItemAction){
                debugItem.selectItemAction(debugItem,indexPath.row);
            }
        }
            break;
    }
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(unselectDebugRow) object:nil];
    [self performSelector:@selector(unselectDebugRow) withObject:nil afterDelay:0.3];
}
-(void)unselectDebugRow {
    [self.tbvConfigs deselectRowAtIndexPath:[self.tbvConfigs indexPathForSelectedRow] animated:YES];
}

#pragma mark - UIPickerViewDataSource
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    BCDebugItemModel *debugItem = (BCDebugItemModel *)pickerView.kdhData;
    if(debugItem){
        return debugItem.bcOptions.count;
    }
    return 0;
}
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 1;
}
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    BCDebugItemModel *debugItem = (BCDebugItemModel *)pickerView.kdhData;
    if(!debugItem.bcOptions){
        return nil;
    }
    if(debugItem.bcOptions.count <= row){
        return nil;
    }
    BCDebugItemOption *debugOption = (BCDebugItemOption *)[debugItem.bcOptions objectAtIndex:row];
    return debugOption.bcName;
}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    BCDebugItemModel *debugItem = (BCDebugItemModel *)pickerView.kdhData;
    if(debugItem.bcOptions.count <= row){
        return ;
    }
    debugItem.bcSelectOptionIndex = row;
    if(debugItem.selectOptionAction){
        BCDebugItemOption *debugOption = (BCDebugItemOption *)[debugItem.bcOptions objectAtIndex:row];
        debugItem.selectOptionAction(debugItem,debugOption,row);
    }
    [self reloadDebugConfig];
    [self.tbvConfigs reloadData];
}

//MARK: - Event
- (void)onTableTapGesture:(UITapGestureRecognizer *)gesture {
    if (_pvSwitch != nil && _pvSwitch.superview != nil) {
        [_pvSwitch removeFromSuperview];
    }
}

@end
